package com.macrosolution.exdebito


import java.text.SimpleDateFormat;

import grails.plugin.springsecurity.annotation.Secured;
import grails.transaction.Transactional;
import grails.converters.JSON;

@Secured(['ROLE_ADMIN','ROLE_AMM'])
class UserController extends grails.plugin.springsecurity.ui.UserController {
	
	def springSecurityService
	
	def show(){
		
	}

	@Transactional
	def save(){
	User secUser =springSecurityService.currentUser
	String born= params.born
	Long province =params.getLong('bornProvince')
	params.remove('bornProvince')
	params.remove('born')
	Long born_municipality =params.getLong('born_municipality')
	println born_municipality
	params.remove('born_municipality')

	User user
	if(params.user_id){
		user=User.get(params.getLong('user_id'))
		
		user.setProperties(params)
		user.fiscalAddress.save(flush:true)
	}else{
		
		user= User.newInstance(params)
		user.fiscalAddress.save(flush:true)
	}
	if(born && !born.isEmpty()){
		user.born=new SimpleDateFormat('dd/MM/yyyy').parse(born)
	}
	if(province && province>0){
		user.bornProvince = Provincia.get(province)
	}
	if(born_municipality && born_municipality>0) {		
		user.bornMunicipality = Comune.get(born_municipality)
		user.bornCap = (Comune.get(born_municipality)).cap
	}
	User owner = User.get(params.getLong('owner'))
	Role role = Role.get(params.getLong('role_id'))
	if (!user.save(flush: true)) {
		List roles=Role.findAllByPriority((role.priority-1));
		List owners = new ArrayList<User>();
		if(roles){
			for(Role r:roles){
				if(!(r.label.equals("AVVOCATO"))){
					def users= secUser.getSubjectsByRole(r)
					owners.addAll(users)
				}
			}
		}
		render template: 'edit', model: [user: user, role: role,owners:owners,owner_selected:params.owner]
		return
	}
	if(!params.user_id){
	UserRole userRole = new UserRole()
	userRole.create(user, role).save(flush:true)
	
	}
	if(!owner.subjects){
		owner.subjects=new ArrayList<User>()
	}
		
		if(!owner.subjects.contains(user)){
			owner.addSubject(user);
			owner.save(flush: true);
		}
	redirect uri:'/user/get_users_role?role='+role.id
	}
	
	def edit(){
		User user;
		User parent;
		User secUser =springSecurityService.currentUser
		if(params.id){
			user=User.get(params.getLong('id'))
			if(user){
				parent = user.owner
				if(!parent){
					parent =secUser.getParent(user)
				}
				
			}
		}
		Role role;
		if(params.id_role){
			role=Role.get(params.getLong('id_role'))
		}
		if(role){
			if(!secUser.checkAddRole(role)){
				render '<div class="alert alert-warning fade in">Non ci sono utenti con un ruolo superiore a '+role.label+'</div>'
				return
			}
		}
		
		List roles=Role.findAllByPriority((role.priority-1));
		List owners = new ArrayList<User>();
		if(roles){
			for(Role r:roles){
				if(!(r.label.equals("AVVOCATO"))){
					def users= secUser.getSubjectsByRole(r)
					owners.addAll(users)
				}
			}
		}		
		render template:'edit',model:[user:user,role:role,owners:owners,owner_selected:parent?.id]
	}
	
	@Transactional
	def delete(User user){
		def username=user.username
		UserRole uRole = UserRole.findByUser(user);
		Role role=uRole.getRole()
		
		if(user){
			User parent
			if(user.owner){
				 parent=user.owner
			}else{
				 parent=user.getParent(user);
			}
			if(parent){
				parent.removeFromSubjects(user);
				parent.save()
			}
			uRole.delete()
			if(!user.delete()){
				render '<div class="alert alert-warning fade in">Questo utente non pu&ograve; essere cancellato perch&egrave; &egrave; associato ad interviste e/o pratiche</div>'
				return
			}
			
		}
		List usersRole = UserRole.findAllByRole(role);
		User secUser =springSecurityService.currentUser
		List users = secUser.getSubjectsByRole(role);
		if(users){
			flash.message = 'Utente '+username+' è stato cancellato'
			render template:'list',model:[users:users,role:role]
		}else{
		render '<div class="alert alert-warning fade in">Non ci sono utenti con il ruolo '+role.label+'<button type="button" class="btn btn-info btn-sm col-md-offset-1" id="add_user" onclick="showEditUser(-1,'+role.id+');"><i class="fa fa-plus-circle"></i>&nbsp;&nbsp;Aggiungi '+role.label+'</button></div>'
		}		
	}
	
	def get_users_role(){
		Role role=Role.get(params.getLong('role'));
		User secUser =springSecurityService.currentUser
		List users = secUser.getSubjectsByRole(role);
		if(users){
			render template:'list',model:[users:users,role:role]
			return
		}else{
			render '<div class="alert alert-warning fade in">Non ci sono utenti con il ruolo '+role.label+'<button type="button" class="btn btn-info btn-sm col-md-offset-1" id="add_user" onclick="showEditUser(-1,'+role.id+');"><i class="fa fa-plus-circle"></i>&nbsp;&nbsp;Aggiungi '+role.label+'</button></div>'
		}
	}
	//used by jquery vlidator in remote function
	def check_unique={
		boolean result=true
		User user = User.findByUsername(params.code);
		if(user){
			result=false;
		}
		render result	
	}
	
	@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_BCKOFF','ROLE_AVV','ROLE_CC','ROLE_C','ROLE_SC'])
	def get_user_json(){
		def usr = User.get(params.userId)
		JSON.use("deep") {
				render usr as JSON
		}
	}
	@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_BCKOFF','ROLE_AVV','ROLE_CC','ROLE_C','ROLE_SC'])
	def get_parent_json(){
		def usr = User.get(params.userId)
		if(usr.owner){
		JSON.use("deep") {
				render usr.owner as JSON
		}
		
		}else{
		render get_user_json();
		}
		
	}
	
}

